package com.ruoyi.web.controller.food;

import com.ruoyi.common.utils.vosk.VoiceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

@RestController
@RequestMapping("/voice")
public class VoiceAiController {

    @Autowired
    VoiceUtil voiceUtil;

    @PostMapping("/getWord")
    public String getWord(@RequestParam("file") MultipartFile file) {
        String path = "D:\\leenleda\\application\\voice-ai\\" + new Date().getTime() + ".wav";
        File localFile = new File(path);
        try {
            Path path1 = Paths.get(path);
            path1.getParent().toFile().mkdirs();
            file.transferTo(localFile); //把上传的文件保存至本地
            System.out.println(file.getOriginalFilename() + " 上传成功");
            // 上传成功，开始解析
            String text = voiceUtil.getWord(path);
            localFile.delete();
            return text;
        } catch (IOException | UnsupportedAudioFileException e) {
            e.printStackTrace();
            localFile.delete();
            return "上传失败";
        }
    }
}

